const getClass = require('../../lib/getClass')
const logger = require('log4js').getLogger()

module.exports = (resolve, reject, url, data) => {
  var obj = {}
  resolve = resolve || (() => {})
  reject = reject || (() => {})
  if (getClass(resolve) != 'Function') {
    obj = resolve
    resolve = obj.resolve
    reject = obj.reject
    url = obj.url
    data = obj.data
  }
  const urlObj = require('url').parse(url, true);
  var options = {
    host: urlObj.hostname,
    port: urlObj.port,
    path: urlObj.pathname + (urlObj.search ? urlObj.search : ''),
    method: !!data ? 'POST' : 'GET',
  }
  if (!!data) {
    options.headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF8',
      'Content-Length': Buffer.byteLength(data)
    }
  }
  if (obj.headers && options.headers) {
    for (var key in obj.headers) {
      options.headers[key] = obj.headers[key]
    }
  }
  if (obj.key && obj.cert) {
    options.key = obj.key
    options.cert = obj.cert
  }
  var promise = new Promise((resolve, reject) => {
    const req = (urlObj.protocol == 'https:' ? require('https') : require('http')).request(options, (res) => {
      if (res.statusCode == 301 || res.statusCode == 302) {
        if (!res.headers.location) {
          reject()
          logger.debug('[' + __filename + ':' + __line + ']', res.headers)
          return
        }
        obj.url = res.headers.location
        module.exports(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
        return
      }
      var body = []
      res.on('data', (chunk) => {
        body.push(chunk)
      }).on('end', () => {
        var html = Buffer.concat(body).toString(),
          start = 0,
          _start,
          meta;
        while ((start = html.indexOf('<meta ', start)) != -1) {
          meta = html.substring(start, html.indexOf('>', start + 6) + 1);
          if ((_start = meta.indexOf('charset=')) != -1) {
            _start += 8
            if (meta.substring(_start, _start + 1) == '"')
              _start++;
            if (meta.substring(_start, _start + 6) == 'gb2312' || meta.substring(_start, _start + 3) == 'gbk') {
              html = require('iconv-lite').decode(Buffer.concat(body), 'GBK');
              break
            }
          }
          start += meta.length
        }
        resolve(html);
      }).on('error', (err) => {
        logger.error('[' + __filename + ':' + __line + ']', err)
        reject(err)
      })
    }).on('error', (err) => {
      reject(err)
    })
    if (!!data)
      req.end(data)
    else
      req.end()
  })
  if (resolve) {
    promise.then(resolve, reject)
  } else {
    return promise
  }
}